package com.kangrui.lucene.pinyin;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.CharTermAttributeImpl;

/**
 * 拼音NGram分词过滤器
 * @author Administrator
 *
 */
public final class PinyinNGramTokenFilter extends TokenFilter {
	
	private final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class);
	
	private char[] currTermBuffer;
	private int currTermLength;
	private int currSize = 1;
	private int minPos;
	private int maxPos;

	public PinyinNGramTokenFilter(TokenStream input) {
		super(input);
	}
	
	public PinyinNGramTokenFilter(TokenStream input, int minPos, int maxPos) {
		super(input);
		if(minPos<1)	minPos = 1;
		if(minPos<maxPos) {
			this.minPos = minPos;
			this.currSize = minPos;
			this.maxPos = maxPos;
		}
	}

	@Override
	public boolean incrementToken() throws IOException {
		if(currTermBuffer==null) {
			if(input.incrementToken()) {
				if(!isContainChinese(termAtt.toString())) {
					CharTermAttributeImpl termAttr = (CharTermAttributeImpl)termAtt;
					currTermBuffer = termAttr.clone().buffer();
					currTermLength = termAttr.length();
				}
				return true;
			} else {
				return false;
			}
		} else {
			char[] ngramChars = new char[currSize];
			System.arraycopy(currTermBuffer, 0, ngramChars, 0, currSize);
			termAtt.copyBuffer(ngramChars, 0, currSize);
			int currMaxPos = maxPos==0||maxPos>currTermLength-1?currTermLength-1:maxPos;
			if(currSize==currMaxPos) {
				currTermBuffer = null;
				currSize = minPos;
			}
			currSize++;
			return true;
		}
	}
	
	public static boolean isContainChinese(String str) {
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        if (m.find()) {
            return true;
        }
        return false;
    }
	
	public static void printArray(char[] objs) {
		for(Object obj : objs) {
			System.out.println(obj);
		}
	}
  
}
